package com.tianxin.workbao.workBao.dataProvide;

import android.content.Context;

import com.tianxin.workbao.workBao.R;
import com.tianxin.workbao.workBao.bean.CarInformation;
import com.tianxin.workbao.workBao.bean.CarInformationDao;
import com.tianxin.workbao.workBao.common.Constant;
import com.tianxin.workbao.workBao.common.URL;
import com.tianxin.workbao.workBao.helper.GreenDaoHelper;
import com.tianxin.workbao.workBao.listener.UpdateListViewListener;
import com.tianxin.workbao.workBao.okhttp.CommonOkHttpClient;
import com.tianxin.workbao.workBao.okhttp.exception.OkHttpException;
import com.tianxin.workbao.workBao.okhttp.listener.DisposeDataHandle;
import com.tianxin.workbao.workBao.okhttp.listener.DisposeDataListener;
import com.tianxin.workbao.workBao.okhttp.request.CommonRequest;
import com.tianxin.workbao.workBao.okhttp.request.RequestParams;
import com.tianxin.workbao.workBao.utils.common.BeansUtil;
import com.tianxin.workbao.workBao.utils.common.NetworkUtils;
import com.tianxin.workbao.workBao.utils.common.UIUtils;

import org.greenrobot.greendao.query.Query;
import org.greenrobot.greendao.query.WhereCondition;
import org.json.JSONException;
import org.json.JSONObject;

import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * Created by hacker on 2017/7/14.
 */

public class CarProvide extends BaseDataProvide {
    private Integer mPage = 1;
    private List<CarInformation> mCarInfors;
    private CarInformation mCarInformation;
    private int isFromServer;
    private UpdateListViewListener mUpdateListViewListener;
    private CarInformationDao carInforDao;
    private boolean isGetSingleData = false;

    public CarProvide(Context context, UpdateListViewListener listener) {
        super(context);
        mUpdateListViewListener = listener;
        isFromServer = 0;
        carInforDao = GreenDaoHelper.newInstance().getDaoSession().getCarInformationDao();
    }

    private void getFromDb(int page) {
        CarInformationDao carInforDao = mGreenDaoHelper.getDaoSession().getCarInformationDao();
        Query<CarInformation> query = carInforDao.queryBuilder().where(CarInformationDao.Properties.Isis.eq(1))
                .offset((page - 1) * Constant.COAL_PAGE_SIZE)
                .limit(Constant.COAL_PAGE_SIZE)
                .build();
        mCarInfors = query.list();
    }

    @Override
    public DisposeDataHandle getDisposeDataHandle() {
        disposeDataHandle = new DisposeDataHandle(getDisposeDataListener());
        return disposeDataHandle;
    }

    @Override
    public DisposeDataListener getDisposeDataListener() {
        disposeDataListener = new DisposeDataListener() {
            @Override
            public void onSuccess(Object responseObj) {
                mUpdateListViewListener.hideProgress();
                try {
                    JSONObject object = new JSONObject(responseObj.toString());
                    int status = object.getInt(Constant.RESPONSE_STATUS);
                    String information = object.getString(Constant.RESPONSE_INFO);
                    if (status > 0) {
                        String dataJson = object.getString(Constant.RESPONSE_DATA);
                        if (dataJson != null || dataJson.length() > 2) {
                            try {
                                if (dataJson.startsWith("[") && dataJson.endsWith("]") && dataJson.length() > 3) {
                                    if (dataJson.length() < 3) {
                                        mUpdateListViewListener.showMessage(information + " \n没有数据！");
                                    } else {
                                        if (mCarInfors != null && !mCarInfors.isEmpty()) {
                                            mCarInfors.clear();
                                        }
                                        mCarInfors = BeansUtil.carToBeans(dataJson);
                                        refreshUI();
                                        saveToDb(mCarInfors);
                                    }
                                } else {
                                    mCarInformation = BeansUtil.carToBean(dataJson);
                                    refreshUI();
                                    saveToDb(mCarInformation);
                                }
                            } catch (Exception e) {
                                mUpdateListViewListener.showMessage("car To Bean Error :类型转换出错" + e.getMessage());
                            }

                        } else {
                            mUpdateListViewListener.showMessage(information);
                        }
                    } else {
                        mUpdateListViewListener.showMessage(information);
                    }

                } catch (JSONException e) {
                    showRequestErrorMessage(mUpdateListViewListener, responseObj.toString());
                    e.printStackTrace();
                }
            }

            @Override
            public void onFailure(Object reasonObj) {
                mUpdateListViewListener.hideProgress();
                if (reasonObj instanceof OkHttpException) {
                    OkHttpException exception = (OkHttpException) reasonObj;
                    mUpdateListViewListener.showMessage(exception.getEcode() + ":" + exception.getEmsg().toString());
                } else {
                    showRequestErrorMessage(mUpdateListViewListener, reasonObj.toString());
                }
            }
        };
        return disposeDataListener;
    }

    /**
     * true save data to databases
     *
     * @param obj
     */
    private void saveToDb(Object obj) {
        if (obj instanceof List) {
            for (int i = 0; i < mCarInfors.size(); i++) {
                carInforDao.insertOrReplace(mCarInfors.get(i));
            }
        } else {
            carInforDao.insertOrReplace((CarInformation) obj);
        }
    }

    /**
     * get coals 获取 车辆 列表 Information
     *
     * @param page
     */
    public void getCarInformations(int page) {
        mPage = page;
        isGetSingleData = false;
        getFromDb(page);
        if (mCarInfors == null || mCarInfors.isEmpty()) {
            if (isFromServer == 0) {
                updateFromServer();
            }
        } else {
            refreshUI();
        }

    }

    /**
     * update the coal data  from server
     */
    private void updateFromServer() {
        if (!NetworkUtils.isConnected(UIUtils.getContext())) {
            mUpdateListViewListener.hideProgress();
            mUpdateListViewListener.showMessage(mContext.getResources().getString(R.string.poor_network));
        } else {
            mUpdateListViewListener.showProgress();
            isFromServer = 1;
            Map<String, String> map = new HashMap<>();
            map.put(Constant.APPTOKEN_NAME, getAppToken());
            RequestParams params = new RequestParams(map);
            CommonOkHttpClient.post(CommonRequest.createPostRequest(URL.getCarsUrl(), params), getDisposeDataHandle());
        }
    }

    @Override
    public void refreshUI() {
        if (isGetSingleData == true) {
            mUpdateListViewListener.onRefreshData(mCarInformation);
            return;
        }
        if (mCarInfors != null && !mCarInfors.isEmpty()) {
            if (mPage > 1) {
                mUpdateListViewListener.onLoadMoreData(mCarInfors);
            } else {
                mUpdateListViewListener.onRefreshData(mCarInfors);
            }
        }
    }

    public void getcarBycpunumber(String cpuCardNumber) {
        isGetSingleData = true;
        if (!NetworkUtils.isConnected(UIUtils.getContext())) {
            mUpdateListViewListener.hideProgress();
            mUpdateListViewListener.showMessage(mContext.getResources().getString(R.string.poor_network));
            Query<CarInformation> query = carInforDao.queryBuilder()
                    .where(CarInformationDao.Properties.Cpucardnumber.eq(cpuCardNumber)).limit(1).build();
            List<CarInformation> list = query.list();
            if (list.size() > 0) {
                mCarInformation = list.get(0);
            }
            refreshUI();
        } else {
            mUpdateListViewListener.showProgress();
            isFromServer = 1;
            Map<String, String> map = new HashMap<>();
            map.put(Constant.APPTOKEN_NAME, getAppToken());
            map.put("cpunumber", cpuCardNumber);
            RequestParams params = new RequestParams(map);
            CommonOkHttpClient.post(CommonRequest.createPostRequest(URL.getCarCpuUrl(), params), getDisposeDataHandle());
        }
    }

    public void getcarByPlateNumber(String carNumber) {
        isGetSingleData = true;
        if (!NetworkUtils.isConnected(UIUtils.getContext())) {
            mUpdateListViewListener.hideProgress();
            mUpdateListViewListener.showMessage(mContext.getResources().getString(R.string.poor_network));
            Query<CarInformation> query = carInforDao.queryBuilder()
                    .where(CarInformationDao.Properties.Cpucardnumber.eq(carNumber)).build();
            mCarInfors = query.list();
            refreshUI();
        } else {
            mUpdateListViewListener.showProgress();
            isFromServer = 1;
            Map<String, String> map = new HashMap<>();
            map.put(Constant.APPTOKEN_NAME, getAppToken());
            map.put("plate", carNumber);
            RequestParams params = new RequestParams(map);
            CommonOkHttpClient.post(CommonRequest.createPostRequest(URL.getCarPlateNumberUrl(), params), getDisposeDataHandle());
        }
    }

    public void getCarinformationsLikeQueryString(String queryString) {
        isGetSingleData = false;
        if (!NetworkUtils.isConnected(mContext)) {
            mUpdateListViewListener.showMessage(
                    mContext.getResources().getString(R.string.poor_network)
            );
            Query<CarInformation> query = carInforDao.queryBuilder()
                    .where(CarInformationDao.Properties.Isis.eq(1))
                    .where(CarInformationDao.Properties.Platenumbers.like("%" + queryString + "%")).build();
            mCarInfors = query.list();
            refreshUI();
        } else {
            mUpdateListViewListener.showProgress();
            isFromServer = 1;
            Map<String, String> map = new HashMap<>();
            map.put(Constant.APPTOKEN_NAME, getAppToken());
            map.put("plate", "%" + queryString + "%");
            RequestParams params = new RequestParams(map);
            CommonOkHttpClient.post(CommonRequest.createPostRequest(URL.getIndistinctCarUrl(), params), getDisposeDataHandle());
        }

    }

    public void search(String query) {
        if (mCarInfors != null) {
            mCarInfors.clear();
            mPage = 1;
        }
        String where = "";
        if (query.length() > 2) {
            where = "platenumbers like '%" + query + "%'";
        } else {
            mUpdateListViewListener.showMessage("输入有错！");
        }
        if (where.length() < 1) return;
        Query<CarInformation> userQuery = carInforDao.queryBuilder()
                .where(new WhereCondition.StringCondition(where))
                .orderAsc(CarInformationDao.Properties.Platenumbers)
                .build();
        mCarInfors = userQuery.list();
        refreshUI();
    }
}
